/*
 * // +-------------------------------------------------------------------------------------------------
 * // |                 有你就好 [ 有节骨乃坚，无心品自端 ]     <http://encoding.wang>
 * // +-------------------------------------------------------------------------------------------------
 * // |                             独在异乡为异客         每逢佳节倍思亲
 * // +-------------------------------------------------------------------------------------------------
 * // |                 联系:   <707069100@qq.com>      <http://weibo.com/513778937>
 * // +-------------------------------------------------------------------------------------------------
 */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                   ErYang出品 属于小极品          共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------


package wang.encoding.mroot.common.service

import com.baomidou.mybatisplus.mapper.EntityWrapper
import com.baomidou.mybatisplus.plugins.Page
import com.baomidou.mybatisplus.service.impl.ServiceImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import wang.encoding.mroot.common.config.AesManageConfiguration
import wang.encoding.mroot.common.config.DigestManageConfiguration
import wang.encoding.mroot.common.config.LocaleMessageSourceConfiguration
import wang.encoding.mroot.common.mapper.SuperMapper
import wang.encoding.mroot.common.task.CommonAsyncTask
import wang.encoding.mroot.common.util.MybatisPlusUtil
import wang.encoding.mroot.model.enums.StatusEnum
import java.io.Serializable
import java.time.Instant
import java.util.*


/**
 * 基类 service 实现
 *
 * @author ErYang
 */
open class BaseServiceImpl<M : SuperMapper<T>, T> : ServiceImpl<M, T>(), BaseService<T> {


    @Suppress("SpringKotlinAutowiredMembers")
    @Autowired
    protected val superMapper: M? = null

    @Suppress("SpringKotlinAutowiredMembers")
    @Autowired
    protected lateinit var localeMessageSourceConfiguration: LocaleMessageSourceConfiguration

    @Suppress("SpringKotlinAutowiredMembers")
    @Autowired
    protected lateinit var applicationContext: ApplicationContext

    @Suppress("SpringKotlinAutowiredMembers")
    @Autowired
    protected lateinit var commonAsyncTask: CommonAsyncTask

    @Suppress("SpringKotlinAutowiredMembers")
    @Autowired
    protected lateinit var digestManageConfiguration: DigestManageConfiguration

    @Suppress("SpringKotlinAutowiredMembers")
    @Autowired
    protected lateinit var aesManageConfiguration: AesManageConfiguration

    /**
     * 查询总数
     *
     * @param whereMap: Map<String, Any>
     * @return T
     */
    override fun count(whereMap: Map<String, Any>?): Int? {
        // 构建 EntityWrapper
        val entityWrapper = EntityWrapper<T>()
        // 创建条件集合
        if (null != whereMap && whereMap.isNotEmpty()) {
            for ((key: String, value: Any) in whereMap) {
                entityWrapper.eq(key, value)
            }
        }
        return superMapper!!.selectCount(entityWrapper)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 id 查询 T
     *
     * @param id ID
     * @return T
     */
    override fun getById(id: Any): T? {
        return superMapper?.selectById(id as Serializable)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 t 对象查询 T
     * @param t 对象
     * @return T
     */
    override fun getByModel(t: T): T? {
        return superMapper?.selectOne(t)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 新增 T
     * @param t T
     *
     * @return Int
     */
    override fun save(t: T): Int? {
        return superMapper?.insert(t)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 id 删除 T
     * @param id Any
     *
     * @return Int
     */
    override fun removeById(id: Any): Int? {
        return superMapper?.deleteById(id as Serializable)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 id 批量删除
     * @param idArray List<Any>
     *
     * @return Int 删除的行数
     */
    override fun removeBatchById(idArray: List<Any>): Int? {
        val params = HashMap<String, Any>()
        params["idArray"] = idArray
        return superMapper?.removeBatchById(params)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 删除(更新状态) T
     * @param t T
     *
     * @return Int
     */
    override fun remove2StatusById(t: T): Int? {
        return superMapper?.updateById(t)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 恢复(更新状态) T
     * @param t T
     *
     * @return Int
     */
    override fun recover2StatusById(t: T): Int? {
        return superMapper?.updateById(t)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 批量删除(更新状态)
     *
     * @param idArray List<Any>
     * @return Boolean
     */
    override fun removeBatch2UpdateStatus(idArray: List<Any>): Boolean? {
        val params = HashMap<String, Any>()
        params["status"] = StatusEnum.DELETE.key
        params["idArray"] = idArray
        params["gmtModified"] = Date.from(Instant.now())
        return superMapper?.updateBatchStatusById(params)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 批量恢复(更新状态)
     *
     * @param idArray List<Any>
     * @return Boolean
     */
    override fun recoverBatch2UpdateStatus(idArray: List<Any>): Boolean? {
        val params = HashMap<String, Any>()
        params["status"] = StatusEnum.NORMAL.key
        params["idArray"] = idArray
        params["gmtModified"] = Date.from(Instant.now())
        return superMapper?.updateBatchStatusById(params)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 查询 Page 结果集
     *
     * 只有当排序字段有值，排序才会生效
     *
     * @param page   Page<T>
     * @param orderByField   排序字段
     * @param isAsc  是否正序 默认正序
     * @param t   实体类
     * @return Page<T>
     */
    override fun list2page(page: Page<T>, t: T, orderByField: String?, isAsc: Boolean): Page<T>? {
        if (null != orderByField && orderByField.isNotBlank()) {
            page.orderByField = orderByField
        }
        page.isAsc = isAsc
        page.records = superMapper?.list2Page(page, t)
        return page
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 得到所有  T 集合
     * @param t  T
     * @return List< T> 集合
     */
    override fun listByT(t: T): List<T>? {
        return if (null != t) {
            superMapper?.listByT(t)
        } else {
            null
        }
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 查询 list 结果集
     *
     * @param whereMap 查询条件集合
     * @param columnArray 查询字段集合
     *
     * @return List<T>
     */
    override fun list(whereMap: Map<String, Any>, columnArray: Array<String>?): List<T>? {
        // 构建 EntityWrapper
        val entityWrapper = EntityWrapper<T>()
        if (null != columnArray && columnArray.isNotEmpty()) {
            entityWrapper.sqlSelect = MybatisPlusUtil.initSqlSelect(columnArray)
        }
        // 创建条件集合
        if (whereMap.isNotEmpty()) {
            for ((key: String, value: Any) in whereMap) {
                entityWrapper.eq(key, value)
            }
        }
        return superMapper?.selectList(entityWrapper)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 判断对象的属性值是否唯一
     *
     * 在修改对象的情景下
     * 如果属性新修改的值 value 等于属性原来的值 oldValue 则不作比较
     *
     * @param property 字段
     * @param newValue 新值
     * @param oldValue 旧值
     * @return true (不存在)/false(存在)
     */
    override fun propertyUnique(property: String, newValue: Any, oldValue: Any): Boolean {
        if (newValue == oldValue) {
            return true
        }
        val map = HashMap<String, Any>()
        map[property] = newValue
        val list: List<T> = superMapper!!.selectByMap(map)
        if (list.isNotEmpty()) {
            return false
        }
        return true
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 得到最大 sort 值
     *
     * @return Int
     */
    override fun getMax2Sort(): Int {
        var index: Int? = superMapper!!.getMax2Sort()
        if (null == index || 0 > index) {
            index = 0
        }
        return index
    }

    // -------------------------------------------------------------------------------------------------

}

// -----------------------------------------------------------------------------------------------------

// End BaseServiceImpl class

/* End of file BaseServiceImpl.kt */
/* Location: ./src/main/kotlin/wang/encoding/mroot/common/service/BaseServiceImpl.kt */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                           ErYang出品 属于小极品  O(∩_∩)O~~   共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------
